using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.BusLogic;

using ctsu.BaseForms;
using ctsu.Security;
using ctsu.Data;

namespace ctsu.Admin.Forms
{
	public class FormCoreLabQueryLocation : ctsu.BaseForms.FormBase2
	{
		#region members
		public event BusinessLogicEvents.BLGridViewEventHandler GridView;

		private FormMain _main;
		private FormInfoBase _formInfo;
		private Permission _formSecurity;
		private Hashtable _configData;
		//private DataView _dataView;
		//private DataTable _dataTable;
		//private bool _gettingResults;

		//printing
		private PrintDialog _pDlg;
		private PrintDocument _pDoc;
		private int _page;
		private int _startRow;
		private StringBuilder _criteria;
		//private StringBuilder _resultsCriteria;

		FormGrid _fg;
		#endregion members

		#region windows controls
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.Button RunQuery;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ComboBox Tests;
		private System.Windows.Forms.ComboBox Patients;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.Label label1;
		public System.Windows.Forms.ListView lvw;
		private System.Windows.Forms.ColumnHeader columnHeader1;
		private System.Windows.Forms.ColumnHeader columnHeader2;
		private System.Windows.Forms.ColumnHeader columnHeader3;
		private System.Windows.Forms.ColumnHeader columnHeader4;
		private System.Windows.Forms.ColumnHeader columnHeader5;
		private System.Windows.Forms.ListBox Results;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.CheckBox chkLocation;
		private System.Windows.Forms.CheckBox chkContents;
		private System.Windows.Forms.ComboBox Protocols;
		private System.Windows.Forms.ColumnHeader columnHeader6;
		private System.Windows.Forms.ColumnHeader columnHeader7;
		private System.ComponentModel.IContainer components = null;
		#endregion windows controls

		#region initialize
		public FormCoreLabQueryLocation(FormMain main, FormInfoBase fi, Permission formSecurity, Hashtable configData)
		{

			InitializeComponent();

			this._main = main;
			GridView += new ctsu.BaseForms.BusinessLogicEvents.BLGridViewEventHandler(main.OnGridView);
			this._formInfo = fi;
			this._formSecurity = formSecurity;
			this._configData = configData;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormCoreLabQueryLocation));
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.RunQuery = new System.Windows.Forms.Button();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.Tests = new System.Windows.Forms.ComboBox();
			this.Protocols = new System.Windows.Forms.ComboBox();
			this.Patients = new System.Windows.Forms.ComboBox();
			this.label6 = new System.Windows.Forms.Label();
			this.label1 = new System.Windows.Forms.Label();
			this.lvw = new System.Windows.Forms.ListView();
			this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader5 = new System.Windows.Forms.ColumnHeader();
			this.Results = new System.Windows.Forms.ListBox();
			this.label4 = new System.Windows.Forms.Label();
			this.chkLocation = new System.Windows.Forms.CheckBox();
			this.chkContents = new System.Windows.Forms.CheckBox();
			this.columnHeader6 = new System.Windows.Forms.ColumnHeader();
			this.columnHeader7 = new System.Windows.Forms.ColumnHeader();
			this.pnl2.SuspendLayout();
			this.ButtonGroup.SuspendLayout();
			this.groupBox1.SuspendLayout();
			this.SuspendLayout();
			// 
			// pnl2
			// 
			this.pnl2.Controls.Add(this.label1);
			this.pnl2.Controls.Add(this.lvw);
			this.pnl2.Controls.Add(this.Results);
			this.pnl2.Controls.Add(this.label4);
			this.pnl2.Controls.Add(this.groupBox1);
			this.pnl2.Name = "pnl2";
			this.pnl2.Size = new System.Drawing.Size(736, 256);
			// 
			// btnExit
			// 
			this.btnExit.Name = "btnExit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnCancel
			// 
			this.btnCancel.Name = "btnCancel";
			// 
			// btnSave
			// 
			this.btnSave.Name = "btnSave";
			// 
			// ButtonGroup
			// 
			this.ButtonGroup.Controls.Add(this.chkContents);
			this.ButtonGroup.Controls.Add(this.chkLocation);
			this.ButtonGroup.Name = "ButtonGroup";
			this.ButtonGroup.Size = new System.Drawing.Size(744, 40);
			this.ButtonGroup.Controls.SetChildIndex(this.chkLocation, 0);
			this.ButtonGroup.Controls.SetChildIndex(this.btnSave, 0);
			this.ButtonGroup.Controls.SetChildIndex(this.btnCancel, 0);
			this.ButtonGroup.Controls.SetChildIndex(this.btnExit, 0);
			this.ButtonGroup.Controls.SetChildIndex(this.btnPrint, 0);
			this.ButtonGroup.Controls.SetChildIndex(this.btnGrid, 0);
			this.ButtonGroup.Controls.SetChildIndex(this.chkContents, 0);
			// 
			// btnPrint
			// 
			this.btnPrint.Name = "btnPrint";
			this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
			// 
			// btnGrid
			// 
			this.btnGrid.Name = "btnGrid";
			this.btnGrid.Click += new System.EventHandler(this.btnGrid_Click);
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.Add(this.RunQuery);
			this.groupBox1.Controls.Add(this.label2);
			this.groupBox1.Controls.Add(this.label3);
			this.groupBox1.Controls.Add(this.Tests);
			this.groupBox1.Controls.Add(this.Protocols);
			this.groupBox1.Controls.Add(this.Patients);
			this.groupBox1.Controls.Add(this.label6);
			this.groupBox1.Location = new System.Drawing.Point(8, 8);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(608, 64);
			this.groupBox1.TabIndex = 1;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Search Criteria";
			// 
			// RunQuery
			// 
			this.RunQuery.Location = new System.Drawing.Point(520, 32);
			this.RunQuery.Name = "RunQuery";
			this.RunQuery.TabIndex = 4;
			this.RunQuery.Text = "&Run Query";
			this.RunQuery.Click += new System.EventHandler(this.RunQuery_Click);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 16);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(88, 16);
			this.label2.TabIndex = 2;
			this.label2.Text = "Protocol";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(144, 16);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(88, 16);
			this.label3.TabIndex = 4;
			this.label3.Text = "Test Type";
			// 
			// Tests
			// 
			this.Tests.Location = new System.Drawing.Point(144, 32);
			this.Tests.Name = "Tests";
			this.Tests.Size = new System.Drawing.Size(176, 21);
			this.Tests.TabIndex = 3;
			// 
			// Protocols
			// 
			this.Protocols.Location = new System.Drawing.Point(8, 32);
			this.Protocols.Name = "Protocols";
			this.Protocols.Size = new System.Drawing.Size(121, 21);
			this.Protocols.TabIndex = 1;
			// 
			// Patients
			// 
			this.Patients.Location = new System.Drawing.Point(336, 32);
			this.Patients.Name = "Patients";
			this.Patients.Size = new System.Drawing.Size(176, 21);
			this.Patients.TabIndex = 3;
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(336, 16);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(72, 16);
			this.label6.TabIndex = 30;
			this.label6.Text = "Patient";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(152, 80);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(160, 16);
			this.label1.TabIndex = 53;
			this.label1.Text = "Contents of selected location:";
			// 
			// lvw
			// 
			this.lvw.Activation = System.Windows.Forms.ItemActivation.TwoClick;
			this.lvw.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
				| System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.lvw.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																				  this.columnHeader1,
																				  this.columnHeader2,
																				  this.columnHeader3,
																				  this.columnHeader4,
																				  this.columnHeader5,
																				  this.columnHeader6,
																				  this.columnHeader7});
			this.lvw.FullRowSelect = true;
			this.lvw.GridLines = true;
			this.lvw.HideSelection = false;
			this.lvw.Location = new System.Drawing.Point(152, 96);
			this.lvw.MultiSelect = false;
			this.lvw.Name = "lvw";
			this.lvw.Size = new System.Drawing.Size(576, 144);
			this.lvw.TabIndex = 52;
			this.lvw.View = System.Windows.Forms.View.Details;
			// 
			// columnHeader1
			// 
			this.columnHeader1.Text = "Test ID";
			this.columnHeader1.Width = 48;
			// 
			// columnHeader2
			// 
			this.columnHeader2.Text = "Protocol";
			this.columnHeader2.Width = 41;
			// 
			// columnHeader3
			// 
			this.columnHeader3.Text = "Patient";
			this.columnHeader3.Width = 86;
			// 
			// columnHeader4
			// 
			this.columnHeader4.Text = "Test Type";
			this.columnHeader4.Width = 105;
			// 
			// columnHeader5
			// 
			this.columnHeader5.Text = "Location";
			this.columnHeader5.Width = 135;
			// 
			// Results
			// 
			this.Results.Location = new System.Drawing.Point(8, 96);
			this.Results.Name = "Results";
			this.Results.Size = new System.Drawing.Size(128, 147);
			this.Results.TabIndex = 51;
			this.Results.SelectedIndexChanged += new System.EventHandler(this.Results_SelectedIndexChanged);
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 80);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(141, 16);
			this.label4.TabIndex = 50;
			this.label4.Text = "Location (search results):";
			// 
			// chkLocation
			// 
			this.chkLocation.Checked = true;
			this.chkLocation.CheckState = System.Windows.Forms.CheckState.Checked;
			this.chkLocation.Location = new System.Drawing.Point(408, 16);
			this.chkLocation.Name = "chkLocation";
			this.chkLocation.Size = new System.Drawing.Size(104, 16);
			this.chkLocation.TabIndex = 27;
			this.chkLocation.Text = "Print Locations";
			// 
			// chkContents
			// 
			this.chkContents.Location = new System.Drawing.Point(520, 16);
			this.chkContents.Name = "chkContents";
			this.chkContents.Size = new System.Drawing.Size(104, 16);
			this.chkContents.TabIndex = 28;
			this.chkContents.Text = "Print Contents";
			// 
			// columnHeader6
			// 
			this.columnHeader6.Text = "Vist Date";
			this.columnHeader6.Width = 75;
			// 
			// columnHeader7
			// 
			this.columnHeader7.Text = "Visit";
			// 
			// FormCoreLabQueryLocation
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(744, 302);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "FormCoreLabQueryLocation";
			this.Text = "Core Lab - Query Inventory Location Screen";
			this.Resize += new System.EventHandler(this.FormCoreLabQueryLocation_Resize);
			this.Load += new System.EventHandler(this.FormCoreLabQueryLocation_Load);
			this.pnl2.ResumeLayout(false);
			this.ButtonGroup.ResumeLayout(false);
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		private void FormCoreLabQueryLocation_Load(object sender, System.EventArgs e)
		{
			FillProtocolList();
			FillTestList();
			FillPatientList();
		}

		private void FillProtocolList()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "";

			Protocols.Items.Clear();

			sql = "SELECT DISTINCT d.Protocol " +
				" FROM TestSamples t, DrawSamples d " +
				" WHERE t.Location Is Not Null AND LEN(t.Location)>0 " +
				" AND t.DrawSample = d.ID ORDER BY d.Protocol";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql);	
				reader = DataAccess.GetDataReader(sql);
				Protocols.BeginUpdate();
				Protocols.Items.Add("");
				while (reader.Read())
				{
					Protocols.Items.Add(reader.GetInt32(0).ToString());
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve protocols for Protocol List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Protocol List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Protocols.EndUpdate();
			}
		}

		private void FillTestList()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "";

			Tests.Items.Clear();

			sql = "SELECT DISTINCT tt.Display, t.TestType " +
				" From TestType_L tt, TestSamples t, DrawSamples d " +
				" WHERE t.Location Is Not Null AND LEN(t.Location)>0 " +
				" AND t.DrawSample = d.ID " +
				" AND t.TestType = tt.ID " +
				" ORDER BY tt.Display";

			Forms.NameVal nv = null;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql.ToString());	

				Tests.BeginUpdate();
				Tests.Items.Add("");
				while (reader.Read())
				{
					nv = new NameVal(reader.GetInt32(1), reader.GetString(0));
					Tests.Items.Add(nv);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve tests for Test Type List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Test Type List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Tests.EndUpdate();
			}
		}

		private void FillPatientList()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "";

			Patients.Items.Clear();

			sql = "SELECT DISTINCT d.Patient " +
				" From TestSamples t, DrawSamples d " +
				" WHERE t.Location Is Not Null AND LEN(t.Location)>0 " +
				" AND t.DrawSample = d.ID ORDER BY d.Patient";

			PatientInfo pi = null;
			int id;
			string message = "";
			Forms.NameVal nv = null;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql.ToString());
				Patients.Items.Add(new NameVal(-1, ""));

				Patients.BeginUpdate();
				while (reader.Read())
				{
					id = reader.GetInt32(0);
					message = "";
					pi = CoreLabUtils.GetPatientInfo(id, out message);
					nv = new NameVal(pi.ID, pi.GetNameOrIdentifier());
					Patients.Items.Add(nv);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve patients for Patient List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Patient List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Patients.EndUpdate();
			}
		}
		#endregion initialize

		private void RunQuery_Click(object sender, System.EventArgs e)
		{
			RunQuery.Enabled = false;
			Cursor.Current = Cursors.WaitCursor;
			this.GetResults();
			RunQuery.Enabled = true;
		}

		private void GetResults()
		{
			StringBuilder sb = new StringBuilder();
			StringBuilder sql = new StringBuilder();
			int protocolID = 0;
			int testID = 0;
			int patientID = 0;

			Results.BeginUpdate();
			Results.Items.Clear();
			lvw.Items.Clear();

			if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex < 1 && Patients.SelectedIndex < 1)
			{
				return;
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex < 1 && Patients.SelectedIndex < 1)
			{
				protocolID = Convert.ToInt32(Protocols.Text);
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND d.Protocol=" + protocolID);
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex > 0 && Patients.SelectedIndex < 1)
			{
				protocolID = Convert.ToInt32(Protocols.Text);
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID +
					" AND d.Protocol=" + protocolID);
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex < 1 && Patients.SelectedIndex > 0)
			{
				patientID = ((NameVal)Patients.SelectedItem).Val;
				protocolID = Convert.ToInt32(Protocols.Text);
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND d.Protocol=" + protocolID +
					" AND d.Patient =" + patientID);
			}
			else if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex > 0 && Patients.SelectedIndex < 1)
			{
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID);
			}
			else if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex > 0 && Patients.SelectedIndex > 0)
			{
				patientID = ((NameVal)Patients.SelectedItem).Val;
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID +
					" AND d.Patient =" + patientID);
			}
			else if (Protocols.SelectedIndex < 1 && Tests.SelectedIndex < 1 && Patients.SelectedIndex > 0)
			{
				patientID = ((NameVal)Patients.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND d.Patient =" + patientID);
			}
			else if (Protocols.SelectedIndex > 0 && Tests.SelectedIndex > 0 && Patients.SelectedIndex > 0)
			{
				protocolID = Convert.ToInt32(Protocols.Text);
				patientID = ((NameVal)Patients.SelectedItem).Val;
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append("SELECT DISTINCT t.Location " +
					" From TestSamples t, DrawSamples d " +
					" WHERE t.Location Is Not Null " +
					" AND t.DrawSample = d.ID " +
					" AND t.TestType = " + testID +
					" AND d.Protocol=" + protocolID +
					" AND d.Patient =" + patientID);
			}

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql.ToString());					
				while (reader.Read())
				{
					Results.Items.Add(reader.GetString(0));
				}

				if (Results.Items.Count > 0)
				{
					btnPrint.Enabled = true;
					btnCancel.Enabled = true;
				}
				else
				{
					btnPrint.Enabled = false;
					btnCancel.Enabled = false;
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve results!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Results List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Results.EndUpdate();
			}
		}

		private void Results_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			GetContents();
		}

		private void GetContents()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT DISTINCT t.ID, d.Protocol, d.Patient, " +
				" tt.Display, t.Location, d.VisitDate, d.Visit " +
				" FROM TestSamples t, DrawSamples d, TestType_L tt " +
				" WHERE t.Location = '" + (string)Results.SelectedItem + "' " +
				" AND t.DrawSample = d.ID " +
				" AND t.TestType = tt.ID";

			lvw.BeginUpdate();
			lvw.Items.Clear();
			int patientID;
			string message = "";
			PatientInfo pi = null;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql);	
				reader = DataAccess.GetDataReader(sql.ToString());

				while (reader.Read())
				{
					ListViewItem lvi = new ListViewItem(reader.GetInt32(0).ToString());
					lvi.SubItems.Add(reader.GetInt32(1).ToString());
					patientID = reader.GetInt32(2);
					message = "";
					pi = CoreLabUtils.GetPatientInfo(patientID, out message);
					lvi.SubItems.Add(pi.GetNameOrIdentifier());
					lvi.SubItems.Add(reader.GetString(3));
					lvi.SubItems.Add(reader.GetString(4));
					if (!reader.IsDBNull(5))
						lvi.SubItems.Add(reader.GetDateTime(5).ToShortDateString());
					else
						lvi.SubItems.Add("");
					if (!reader.IsDBNull(6))
						lvi.SubItems.Add(reader.GetString(6));
					else
						lvi.SubItems.Add("");

					lvw.Items.Add(lvi);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve sample!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Retrieve Sample Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				lvw.EndUpdate();
			}
		}

		private void btnExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		#region grid stuff
		private void btnGrid_Click(object sender, System.EventArgs e)
		{
			FormDockingManager fdm = _main.DockManager;

			if (this._fg != null)
			{
				//if its not null then we have already been thru here
				//so just make sure the grid is the active one
				fdm.ActivateDockControl(this._formInfo.TableName);
				return;
			}

			//does the grid exist
			if (fdm.DockControlExists(this._formInfo.TableName))
			{
				//need to get a reference to the formGrid
				_fg = (FormGrid)fdm.GetDockControl(this._formInfo.TableName);
				//make sure it is visible
				if (!fdm.IsDockControlVisible(this._formInfo.TableName))
					fdm.SetDockControlVisibility(this._formInfo.TableName, true);
				//then activate it
				fdm.ActivateDockControl(this._formInfo.TableName);
			}
			else //create it		
			{
				_fg = new FormGrid("SELECT * FROM " + this._formInfo.TableName, this, this._formInfo.TableName);
				_fg.Text = this._formInfo.TableName;
				BLGridViewEventArgs ea = new BLGridViewEventArgs(this._formInfo.TableName, _fg);

				if (GridView != null)
					GridView(this, ea);
				_fg.Show();
			}
			//this is used to set the grid reference to null
			_fg.Closing += new CancelEventHandler(_fg_Closing);
		}

		private void _fg_Closing(object sender, CancelEventArgs e)
		{
			_fg = null;
		}
		#endregion grid stuff

		#region print
		private void btnPrint_Click(object sender, System.EventArgs e)
		{
			if (chkLocation.Checked && Results.Items.Count > 0)
				PrintLocations();

			if (chkContents.Checked && lvw.Items.Count > 0)
				PrintContents();
		}

		private void PrintContents()
		{
			StringBuilder sb = new StringBuilder();

			this._pDoc = new PrintDocument();
			//this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this) == DialogResult.Cancel)
				return;

			Cursor.Current = Cursors.WaitCursor;
			this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage2);

			_page = 1;
			_startRow = 0;
			this._pDoc.Print();
			this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage2);
		}

		private void _pDoc_PrintPage2(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Inventory Location Contents Query Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				PrintingUtils.PrintCenter("For Location: " + Results.SelectedItem.ToString(), e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				sb.Append("Date: " + DateTime.Today.ToShortDateString());
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Inventory Location Contents Query Report - ");
				sb.Append("Date: " + DateTime.Today.ToShortDateString());
				sb.Append("  continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25;  //75
			float c2 = 100; //75
			float c3 = 175; //125			
			float c4 = 300; //150
			float c5 = 450; //150			
			float c6 = 600; //100
			float c7 = 700; //150			

			float c1W = 75;  //id
			float c2W = 75;  //protocol
			float c3W = 125; //patient
			float c4W = 150; //test 
			float c5W = 150; //location
			float c6W = 100; //visit date
			float c7W = 150; //visit


			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("Test ID", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("Protocol", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Test Type", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Location", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Visit Date", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
			gfx.DrawString("Visit", ColumnHeadFont, Brushes.Black, rec);

			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			ListViewItem lvi;
			//string patient;
			string location = "";
			string val = "";

			for (int row = _startRow; row < lvw.Items.Count; row++)
			{
				if (curLine == maxLines)
				{
					_startRow = row;
					this._page++;
					e.HasMorePages = true;
					return;
				}

				lvi = lvw.Items[row];

				val = lvi.Text;
				PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				val = lvi.SubItems[1].Text;
				PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				val = lvi.SubItems[2].Text;
				PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				val = lvi.SubItems[3].Text;
				PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				location = lvi.SubItems[4].Text;
				PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
				gfx.DrawString(location, prntFont, Brushes.Black, rec);

				val = lvi.SubItems[5].Text;
				PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				val = lvi.SubItems[6].Text;
				PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				yPos += lineHeight;
				curLine++;
			}
		}

		private void GetCriteria()
		{
			_criteria = new StringBuilder();
			_criteria.Append("Criteria: ");

			if (Protocols.SelectedIndex > 0)
				_criteria.Append("  Protocol = " + Protocols.Text);

			if (Tests.SelectedIndex > 0)
				_criteria.Append("  Test Type = " + Tests.Text);


			if (Patients.SelectedIndex > 0)
				_criteria.Append("  Patient = " + Patients.Text);
		}

		private void PrintLocations()
		{
			StringBuilder sb = new StringBuilder();

			this._pDoc = new PrintDocument();
			//this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this) == DialogResult.Cancel)
				return;

			GetCriteria();
			Cursor.Current = Cursors.WaitCursor;
			this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);

			_page = 1;
			_startRow = 0;
			this._pDoc.Print();
			this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage);
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Inventory Location Query Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				PrintingUtils.PrintCenter(this._criteria.ToString(), e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				sb.Append("Date: " + DateTime.Today.ToShortDateString());
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Inventory Location Query Report - ");
				sb.Append("Date: " + DateTime.Today.ToShortDateString());
				sb.Append("  continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			float c1 = 25;
			RectangleF rec = new RectangleF();

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, 500);
			gfx.DrawString("Locations", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;
			gfx.DrawLine(pen, c1, yPos, c1 + 100, yPos);

			yPos += lineHeight;

			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			for (int row = _startRow; row < Results.Items.Count; row++)
			{
				if (curLine == maxLines)
				{
					_startRow = row;
					this._page++;
					e.HasMorePages = true;
					return;
				}

				PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, 200);
				gfx.DrawString(Results.Items[row].ToString(), prntFont, Brushes.Black, rec, fmt);
				yPos += lineHeight;

			}



		}
		#endregion print

		private void FormCoreLabQueryLocation_Resize(object sender, System.EventArgs e)
		{
			if (this.Height > 330)
				pnl2.Height = this.Height - 46;
			if (this.Width > 632)
				pnl2.Width = this.Width - 2;
		}


	}
}

